<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <img src="./czbk.jpg" alt="" />
    <h3>一些提示信息</h3>
    <ul>
      <li>浏览器是否支持：<span id="isSupport"></span></li>
      <li>service worker是否注册成功：<span id="isSuccess"></span></li>
      <li>当前注册状态：<span id="state"></span></li>
      <li>当前service worker状态：<span id="swState"></span></li>
    </ul>
    <script>
      function $(selector) {
        return document.querySelector(selector);
      }
      if ('serviceWorker' in navigator) {
        $('#isSupport').innerText = '支持'

        // 开始注册service workers
        navigator.serviceWorker
          .register('./sw-cache.js', {
            scope: './',
          })
          .then(function (registration) {
            $('#isSuccess').innerText = '注册成功';

            var serviceWorker;
            if (registration.installing) {
              serviceWorker = registration.installing;
              $('#state').innerText = 'installing';
            } else if (registration.waiting) {
              serviceWorker = registration.waiting;
              $('#state').innerText = 'waiting';
            } else if (registration.active) {
              serviceWorker = registration.active;
              $('#state').innerText = 'active';
            }
            if (serviceWorker) {
              $('#swState').innerText = serviceWorker.state;
              serviceWorker.addEventListener('statechange', function (e) {
                $('#swState').innerText += '&emsp;状态变化为' + e.target.state;
              });
            }
          })
          .catch(function (error) {
            console.log(error)
            $('#isSuccess').innerText = '注册没有成功';
          });
      } else {
        $('#isSupport').innerText = '不支持';
      }
    </script>
  </body>
</html>
